import { ApiResult } from './../../support/code/ApiResult';
import { handleSql } from 'src/support/untils/sql';
import { FindAllCarModelDto } from './dto/findAll-car_model.dto';
import { Repository } from 'typeorm';
import { CarModel } from './car_model.entity';
import { Injectable } from '@nestjs/common';
import { CreateCarModelDto } from './dto/create-car_model.dto';
import { UpdateCarModelDto } from './dto/update-car_model.dto';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class CarModelService {
  constructor(
    @InjectRepository(CarModel)
    private carModelRepository: Repository<CarModel>,
  ) {}
  // 创建
  create(createCarModelDto: CreateCarModelDto) {
    const entityDto = this.carModelRepository.create(createCarModelDto);
    return this.carModelRepository.save(entityDto);
  }

  // 获取所有汽车型号信息
  async findAll(findAllCarModelDto: FindAllCarModelDto) {
    const { limit = 10, page = 1, brand_id, ...params } = findAllCarModelDto;
    const where = handleSql(params);
    where['brand_id'] = brand_id;
    const result = await this.carModelRepository.findAndCount({
      where: where,
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      list: result[0],
      total: result[1],
    };
  }

  // 根据id获取汽车型号
  findOne(id: number) {
    return this.carModelRepository.findOneById(id);
  }

  async update(id: number, updateCarModelDto: UpdateCarModelDto) {
    const hasEntriy = await this.carModelRepository.findOneById(id);
    if (!hasEntriy) {
      return;
    }
    const updateInfo = this.carModelRepository.merge(
      hasEntriy,
      updateCarModelDto,
    );
    const result = await this.carModelRepository.save(updateInfo);
    return result;
  }

  async remove(id: number) {
    const result = await this.carModelRepository.delete(id);
    return result;
  }
}
